package com.ccnu.sm.controller;

import com.ccnu.sm.aop.RAOPTest;
import com.ccnu.sm.aop.RAOPUser;
import com.ccnu.sm.domain.User;
import com.ccnu.sm.jdbc.RJdbcTemplate;
import com.ccnu.sm.jdbc.RNamedParameterJdbcTemplate;
import com.ccnu.sm.transaction.RTransactionManagement;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

@Controller
@RequestMapping("/login")
public class LoginController {
    private static final Log log = LogFactory.getLog(LoginController.class);

    @Autowired
    private RJdbcTemplate rJdbcTemplate;

    @Autowired
    private RTransactionManagement rTransactionManagement;

    @Autowired
    private RNamedParameterJdbcTemplate rNamedParameterJdbcTemplate;

    @Autowired
    private RAOPUser raopUser;

    @RequestMapping(value = "/")
    public ModelAndView hello() {
        User user = new User();
        user.setLoginname("p4759521");
        user.setPassword("rhj19871020");
        user.setUsername("raohj");
        user.setAge(18);
        log.info("handleRequest 正在被调用");
        ModelAndView mv = new ModelAndView();
        // 以属性模式响应
        mv.addObject("welcomemessage", "Hello Sping MVC");
        // 以对象形式响应
        mv.addObject(user);
        mv.setViewName("welcome");
        return mv;
    }

    /*
     * 功能描述 测试从url ? 获取请求参数
     * @author raohj
     * @date 2019/11/8
     * @descript
     * @params
     * @return
     */
    @RequestMapping("/string_url_RequestParam")
    public String ctlString_url(@RequestParam("user") String user, @RequestParam("password") String password) {
        log.info("user:" + user + "|password:" + password);
        return "success";
    }

    /*
     * 功能描述 测试通过url / 来获得参数
     * @author raohj
     * @date 2019/11/8
     * @descript
     * @params
     * @return
     */

    @RequestMapping("/string_url_pathvalue/{userid}")
    public String ctlString_url_pathvalue(@PathVariable("userid") Integer userid) {
        log.info("userid:" + userid);
        return "success";
    }

    /*
     * 功能描述 测试通过HttpServletRequest来获取参数
     * @author raohj
     * @date 2019/11/8
     * @descript
     * @params
     * @return
     */

    @RequestMapping("/string_request")
    public String ctlString_Request(HttpServletRequest request) {
        Map<String, String[]> paramMap = request.getParameterMap();
        log.info("请求参数");
        for (String s : paramMap.keySet()) {
            String[] values = paramMap.get(s);
            String value = "";
            if (values != null) {
                for (String value1 : values) {
                    value += value1;
                }
            }
            log.info("key:" + s + " value:" + value);
        }
        return "success";
    }

    /*
     * 功能描述 测试从cookie中取值
     * @author raohj
     * @date 2019/11/8
     * @descript
     * @params
     * @return
     */

    @RequestMapping("/cookie")
    public String ctlCookie(@CookieValue(value = "TOKEN", defaultValue = "") String tokenid) {
        log.info("Token:" + tokenid);
        return "success";
    }

    /*
     * 功能描述 设置Json格式
     *  使用@RequestBody将Json对象转换为Java对象
     *  使用JackSon将Java对象转换为String
     * @author raohj
     * @date 2019/11/8
     * @descript
     * @params
     * @return
     */

    @RequestMapping("/json")
    public void ctlJson(@RequestBody User userReq, HttpServletResponse response) throws IOException {
        ObjectMapper mapper = new ObjectMapper();
        log.info("请求参数：" + mapper.writeValueAsString(userReq));


        User user = new User();
        user.setLoginname("p4759521");
        user.setPassword("rhj19871020");
        user.setUsername("raohj");
        user.setAge(18);

        // 设置字符集，否则客户端无法正确解析汉字
        response.setContentType("text/html;charset=UTF-8");
        log.info("应答参数:" + mapper.writeValueAsString(user));
        response.getWriter().println(mapper.writeValueAsString(user));
    }


    /*
     * 功能描述 测试返回Map
     * @author raohj
     * @date 2019/11/8
     * @descript
     * @params
     * @return
     */
    // TODO 尚未成功
    @RequestMapping("/map")
    public Map<String, String> ctlMap() {
        Map<String, String> retMap = new HashMap<>();
        retMap.put("key1", "value1");
        retMap.put("key2", "value2");
        retMap.put("key3", "value3");
        return retMap;
    }

    @RequestMapping("/model")
    public Model ctlModel() {
        return null;
    }

    @RequestMapping("/jdbctemplate")
    public void ctlJdbcTemplate(HttpServletResponse response) throws IOException {
        response.setContentType("text/html;charset=UTF-8");
        response.getWriter().println("获得的cust记录数: " + rJdbcTemplate.test());
    }

    @RequestMapping("/nameparamerjdbctemplate")
    public void ctlNamedParameterJdbcTemplate(HttpServletResponse response) throws IOException {
        response.setContentType("text/html;charset=UTF-8");
        response.getWriter().println("获得的cust记录数: " + rNamedParameterJdbcTemplate.test());
    }

    @RequestMapping("/transaction")
    public void ctlTransaction(HttpServletResponse response){
        rTransactionManagement.testAnnoation();
        response.setContentType("text/html;charset=UTF-8");
        try {
            response.getWriter().println("调用成功");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @RequestMapping("/aop")
    public void ctlAOP(HttpServletResponse response){
        RAOPTest.testAOPCode();
        response.setContentType("text/html;charset=UTF-8");
        try {
            response.getWriter().println("调用成功");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
